<template>
  <div class="page-wrapper page-apply-add">
    <!-- <div class="map-wrapper">
      <MapPosition ref="mapRef"></MapPosition>
    </div> -->
    <div class="msg-box">
      <a-card
        title="用车申请"
        size="small"
        :bordered="false"
        style="margin-bottom: 20px"
      >
        <AddressList1 @change="handleChange"></AddressList1>
      </a-card>
      <van-form>
        <van-cell-group inset>
          <van-field
            v-bind="fieldProps"
            v-model="formModel.department_id"
            name="用车部门"
            label="用车部门"
            placeholder="用车部门"
            required
            @click="handleSelectDept"
          />

          <van-field
            v-bind="fieldProps"
            v-model="formModel.car_count"
            name="car_count"
            label="用车数量"
            type="number"
            :min="0"
            placeholder="用车数量"
          />

          <van-field
            v-bind="fieldProps"
            v-model="formModel.rading_count"
            name="rading_count"
            label="乘车人员"
            placeholder="乘车人员"
          />

          <van-field
            v-bind="fieldProps"
            v-model="formModel.use_user_id"
            name="use_user_id"
            label="要车人"
            placeholder="要车人"
            required
          />

          <van-field
            v-bind="fieldProps"
            v-model="formModel.phone"
            name="phone"
            label="联系电话"
            placeholder="联系电话"
          />

          <van-field
            v-bind="fieldProps"
            v-model="formModel.plan_begin_time"
            name="plan_begin_time"
            label="预计出车时间"
            placeholder="预计出车时间"
            readonly
            required
            @click="handleSelectDate('plan_begin_time')"
          />
          <van-field
            v-bind="fieldProps"
            v-model="formModel.plan_end_time"
            name="plan_end_time"
            label="预计回车时间"
            placeholder="预计回车时间"
            required
            readonly
            @click="handleSelectDate('plan_end_time')"
          />

          <van-field
            v-bind="fieldProps"
            name="use_car_type"
            label="用车类型"
            placeholder="用车类型"
          >
            <template #input>
              <MSelect
                v-model="formModel.use_car_type"
                value-field="dict_value"
                label-field="dict_label"
                result-field="data"
                :api="apiGetDictDataByType"
                :params="{ dict_type: 'yongcheleixing' }"
              ></MSelect>
            </template>
          </van-field>
          <!-- <van-field
            v-bind="fieldProps"
            name="car_model"
            label="车型"
            placeholder="车型"
          >
            <template #input>
              <MSelect
                v-model="formModel.car_model"
                value-field="dict_value"
                label-field="dict_label"
                result-field="data"
                :api="apiGetDictDataByType"
                :params="{ dict_type: 'chexing' }"
              ></MSelect>
            </template>
          </van-field> -->

          <!-- <van-field
            v-bind="fieldProps"
            name="car_type"
            label="车辆类型"
            placeholder="车辆类型"
          >
            <template #input>
              <MSelect
                v-model="formModel.car_type"
                value-field="dict_value"
                label-field="dict_label"
                result-field="data"
                :api="apiGetDictDataByType"
                :params="{ dict_type: 'cheliangleixing' }"
              ></MSelect>
            </template>
          </van-field> -->

          <template v-if="isFast">
            <van-field
              v-bind="fieldProps"
              name="car_id"
              label="车辆"
              placeholder="车辆"
            >
              <template #input>
                <SelectSpaceCarFast
                  v-model="formModel.car_id"
                  :params="{
                    plan_begin_time: formModel.plan_begin_time,
                    plan_end_time: formModel.plan_end_time,
                  }"
                  @change="onCarChange"
                ></SelectSpaceCarFast>
              </template>
            </van-field>

            <van-field
              v-bind="fieldProps"
              name="driver_id"
              label="司机"
              placeholder="司机"
            >
              <template #input>
                <SelectDriver v-model="formModel.driver_id"></SelectDriver>
              </template>
            </van-field>
          </template>

          <van-field
            v-bind="fieldProps"
            v-model="formModel.remark"
            name="备注信息"
            label="备注信息"
            placeholder="备注信息"
          />
        </van-cell-group>
        <div style="margin: 16px">
          <van-button round block type="primary" @click="handleSub">
            提交
          </van-button>
        </div>
      </van-form>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { ref, watch } from 'vue';
  import { useRoute } from 'vue-router';
  import {
    showToast,
    showSuccessToast,
    showLoadingToast,
    closeToast,
  } from 'vant';
  import { debounce } from 'lodash';
  import ModalSelectDate from '@/components/ModalSelectDate/index';
  import ModalSelectDept from '@/components/ModalSelectDept/index';
  import SelectDriver from '@/components/SelectDriver/index.vue';
  import SelectSpaceCarFast from '@/components/SelectSpaceCarFast/index.vue';
  import { apiGetDictDataByType } from '@/api/system';
  import {
    apiAddDispatch,
    apiAddFastDispatch,
    apiGetWillMil,
  } from '@/api/dispatch';

  import MSelect from '@/components/MSelect/index.vue';

  // import MapPosition from './components/MapPosition/index.vue';
  import AddressList1 from './components/AddressList1/index.vue';

  const route = useRoute();

  const fieldProps = ref({
    labelWidth: '120px',
  });

  const isFast = ref(route.query.type === 'fast');
  const formModel = ref<any>({
    department_id: '',
    name: '',
    startTime: '',
    endTime: '',
    use_car_type: '',
    car_model: '',
    car_type: '',
    start: '',
    destination_list: [],
    car_count: 1,
  });
  // const mapRef = ref<any>();

  const onCarChange = (val, valObj) => {
    formModel.value.driver_id = valObj?.driver_id || '';
  };
  const handleChange = (val) => {
    // mapRef.value.setLine(val);
    formModel.value.start = val?.[0]?.text || '';
    if (val?.length > 1) {
      const strs = val.map((t) => t.text);
      formModel.value.destination_list = strs.slice(1);
    }
  };

  const handleSelectDept = () => {
    ModalSelectDept({
      value: formModel.value.department_id,
    }).then((res) => {
      formModel.value.department_id = res;
    });
  };

  const handleSelectDate = (key: string) => {
    ModalSelectDate({
      value: formModel.value[key],
    }).then((res) => {
      formModel.value[key] = res;
    });
  };

  watch(
    () => [formModel.value.start, formModel.value.destination_list],
    debounce(([start, end]) => {
      const endResult = !end?.length ? [] : end.filter((t) => t?.length);
      if (start?.length && endResult.length) {
        apiGetWillMil({
          start,
          destination_list: endResult,
        }).then((res) => {
          formModel.value.expected_mileage = res.data;
        });
      }
    }, 500)
  );

  const handleSub = () => {
    const data = JSON.parse(JSON.stringify(formModel.value));
    if (!data.start) {
      showToast('请选择 出发地');
      return;
    }

    if (!data.destination_list?.length) {
      showToast('请选择 目的地');
      return;
    }
    const result = data.destination_list.some((t) => !t);

    if (result) {
      showToast('有目的地没有填写地点，请填写');
      return;
    }

    if (!data.department_id) {
      showToast('请选择 用车部门');
      return;
    }

    // if (!data.car_count) {
    //   showToast('请填写 用车数量');
    //   return;
    // }

    // if (!data.rading_count) {
    //   showToast('请填写 乘车人员');
    //   return;
    // }

    if (!data.use_user_id) {
      showToast('请填写 要车人');
      return;
    }

    // if (!data.phone) {
    //   showToast('请填写 联系电话');
    //   return;
    // }

    if (!data.plan_begin_time) {
      showToast('请选择 预计出车时间');
      return;
    }

    if (!data.plan_end_time) {
      showToast('请选择 预计回车时间');
      return;
    }

    // if (!data.use_car_type) {
    //   showToast('请选择 用车类型');
    //   return;
    // }

    // if (!data.car_model) {
    //   showToast('请选择 车型');
    //   return;
    // }

    // if (!data.car_type) {
    //   showToast('请选择 车辆类型');
    //   return;
    // }

    // if (!data.remark) {
    //   showToast('请填写 备注信息');
    //   return;
    // }

    if (isFast.value) {
      if (!data.car_id) {
        showToast('请选择 车辆');
        return;
      }

      if (!data.driver_id) {
        showToast('请选择 司机');
        return;
      }
    }

    showLoadingToast({
      message: '加载中...',
      forbidClick: true,
      duration: 0,
    });

    if (isFast.value) {
      data.dispatch_type = '应急调度';
      apiAddFastDispatch(data)
        .then(() => {
          showSuccessToast('提交成功！');
          window.history.go(-1);
        })
        .finally(() => {
          closeToast();
        });
    } else {
      data.dispatch_type = '普通调度';
      apiAddDispatch(data)
        .then(() => {
          showSuccessToast('提交成功！');
          window.history.go(-1);
        })
        .finally(() => {
          closeToast();
        });
    }
  };
</script>

<style lang="less" scoped>
  .page-wrapper {
    height: 100vh;
    display: flex;
    flex-direction: column;
    .map-wrapper {
      flex-shrink: 0;
      width: 100%;
      height: 600px;
    }
    .msg-box {
      flex-shrink: 1;
      width: 100%;
      height: 100%;
      overflow-x: hidden;
      overflow-y: auto;
    }
  }
</style>
